package com.hbsd.paopaobackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hbsd.paopaobackend.common.BaseResponse;
import com.hbsd.paopaobackend.common.ErrorCode;
import com.hbsd.paopaobackend.common.ResultUtils;
import com.hbsd.paopaobackend.common.request.DeleteRequest;
import com.hbsd.paopaobackend.exception.BusinessException;
import com.hbsd.paopaobackend.model.domain.Team;
import com.hbsd.paopaobackend.model.domain.User;
import com.hbsd.paopaobackend.model.domain.UserTeam;
import com.hbsd.paopaobackend.model.dto.TeamQuery;
import com.hbsd.paopaobackend.model.request.Team.TeamAddRequest;
import com.hbsd.paopaobackend.model.request.Team.TeamJoinRequest;
import com.hbsd.paopaobackend.model.request.Team.TeamQuitRequest;
import com.hbsd.paopaobackend.model.request.Team.TeamUploadRequest;
import com.hbsd.paopaobackend.model.vo.TeamUserVO;
import com.hbsd.paopaobackend.service.TeamService;
import com.hbsd.paopaobackend.service.UserService;
import com.hbsd.paopaobackend.service.UserTeamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 队伍接口
 * @author zzh
 */
@Api(tags = "队伍管理接口")
@RestController
@RequestMapping("/team")
// 配置跨域 allowCredentials: 允许携带cookie
@CrossOrigin(origins = {"http://localhost:5173"}, allowCredentials = "true")
public class TeamController {
    @Resource
    private UserService userService;

    @Resource
    private TeamService teamService;

    @Resource
    private UserTeamService userTeamService;


    /**
     * 创建队伍
     * @param teamAddRequest
     * @return
     */
    @ApiOperation(value = "创建队伍", notes = "创建队伍接口 addTeam")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Cookie", value = "Cookie", dataType = "string", paramType = "header")}
    )
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        // 判断队伍是否为空
        if(teamAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍信息不能为空");
        }

        User loginUser = userService.getLoginUser(request);
        Team team = new Team();
        try {
            BeanUtils.copyProperties(team, teamAddRequest);
        } catch (Exception e) {
          throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数复制失败");
        }
        long teamId = teamService.addTeam(team, loginUser);
        return ResultUtils.success(teamId);
    }


    /**
     * 删除队伍
     * @param id
     * @return
     */
    @ApiOperation(value = "删除队伍", notes = "删除队伍接口 deleteTeam")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(long id) {
        // 判断队伍是否存在
        if(id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍不存在");
        }
        boolean result = teamService.removeById(id);
        if(!result) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "删除队伍失败");
        }

        return ResultUtils.success(true);
    }

    /**
     * 查询队伍列表
     * @param teamUploadRequest
     * @return
     */
    @ApiOperation(value = "更新队伍", notes = "更新队伍信息接口 updateTeam")
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUploadRequest teamUploadRequest, HttpServletRequest request) {
        if(teamUploadRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍信息不能为空");
        }

        User loginUser = userService.getLoginUser(request);
        boolean isAdmin = userService.isAdmin(request);

        boolean result = teamService.updateTeam(teamUploadRequest, loginUser, isAdmin);
        return ResultUtils.success(result);
    }

    /**
     * 查询队伍详情数据
     * @param id
     * @return
     */
    @ApiOperation(value = "查询队伍详情", notes = "查询队伍详情接口 getTeamById")
    @GetMapping("/detail")
    public BaseResponse<Team> getTeamById(long id) {
        if(id<=0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if(team == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍不存在");
        }

        return ResultUtils.success(team);
    }

    /**
     * 查询队伍列表
     * @param teamQuery
     * @return
     */

    @ApiOperation(value = "查询队伍列表", notes = "查询队伍列表接口 getTeamList")
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> getTeamList(TeamQuery teamQuery, HttpServletRequest request) {
        // 判断查询条件是否为空
        if(teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "查询条件不能为空");
        }

        boolean isAdmin = userService.isAdmin(request);

        // 执行查询
        List<TeamUserVO> list = teamService.listTeams(teamQuery, isAdmin);

        // 潘顿当前用户算法已加入队伍
        List<Long> teamIdList = list.stream().map(TeamUserVO::getId).collect(Collectors.toList());
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();

        try {
            User loginUser = userService.getLoginUser(request);
            userTeamQueryWrapper.eq("userId", loginUser.getId());
            userTeamQueryWrapper.in("teamId", teamIdList);
            List<UserTeam> userTeams = userTeamService.list(userTeamQueryWrapper);

            // 已加入的队伍 id集合
            Set<Long> hasJoinTeamIdSet = userTeams.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
            list.forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });
        } catch(Exception e) {
//            return ResultUtils.success(list);
        }

        return ResultUtils.success(list);
    }


    /**
     * 分页查询队伍列表
     * @param teamQuery
     * @return
     */
    @ApiOperation(value = "分页查询队伍列表", notes = "分页查询队伍列表接口 getTeamListPage")
    @PostMapping("/list/page")
    public BaseResponse<Page<Team>> getTeamListPage(TeamQuery teamQuery) {
        if(teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "分页信息不能为空");
        }
        Team team = new Team();
        try {
            BeanUtils.copyProperties(team, teamQuery);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "分页信息转换失败");
        }

        long pageNum = teamQuery.getPageNum();
        long pageSize = teamQuery.getPageSize();
        Page<Team> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Team> teamQueryWrapper = new QueryWrapper<>(team);
        Page<Team> resultPage = teamService.page(page, teamQueryWrapper);
        return ResultUtils.success(resultPage);
    }

    /**
     * 加入队伍
     * @param teamJoinRequest
     * @param request
     * @return
     */

    @ApiOperation(value = "加入队伍", notes = "加入队伍接口 joinTeam")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Cookie", value = "Cookie", dataType = "string", paramType = "header")}
    )
    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        if(teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "加入队伍信息不能为空");
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.joinTeam(teamJoinRequest, loginUser);
        return ResultUtils.success(result);
    }


    /**
     * 退出队伍
     * @param teamQuitRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "退出队伍", notes = "退出队伍接口 quitTeam")
    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        if(teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "退出队伍信息不能为空");
        }

        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.quitTeam(teamQuitRequest, loginUser);
        return ResultUtils.success(result);

    }

    /**
     * 解散队伍
     * @param deleteRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "解散队伍", notes = "解散队伍接口 dissolveTeam")
    @PostMapping("/dissolve")
    public BaseResponse<Boolean> dissolveTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        long id = deleteRequest.getId();
        System.out.println("id = " + id);
        if(deleteRequest == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍不存在");
        }

        User loginUser = userService.getLoginUser(request);
        if(loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH, "请先登录");
        }

        boolean result = teamService.dissolveTeam(id, loginUser);
        return ResultUtils.success(result);
    }


    /**
     * 搜索用户所创建的队伍列表
     * @param teamQuery
     * @param request
     * @return
     */
    @ApiOperation(value = "搜索用户所创建的队伍列表", notes = "搜索用户所创建的队伍列表接口 getCreateTeamList")
    @GetMapping("/list/create")
    public BaseResponse<List<TeamUserVO>> getCurrentTeamList(TeamQuery teamQuery, HttpServletRequest request) {
        // 判断查询条件是否为空
        if(teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "查询条件不能为空");
        }

        User loginUser = userService.getLoginUser(request);
        if(loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH, "请先登录");
        }


        // 执行查询
        List<TeamUserVO> list = teamService.listTeams(teamQuery, true);
        return ResultUtils.success(list);
    }

    /**
     * 获取我加入的队伍
     * @param teamQuery
     * @param request
     * @return
     */
    @ApiOperation(value = "获取我加入的队伍", notes = "获取我加入的队伍列表接口 getOthersTeamList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Cookie", value = "Cookie", dataType = "string", paramType = "header")}
    )

    @GetMapping("/list/current/join")
    public BaseResponse<List<TeamUserVO>> getCurrentJoinTeamList(TeamQuery teamQuery, HttpServletRequest request) {
        // 判断查询条件是否为空
        if(teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "查询条件不能为空");
        }

        User loginUser = userService.getLoginUser(request);
        if(loginUser == null) {
            throw new BusinessException(ErrorCode.NO_AUTH, "请先登录");
        }

        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", loginUser.getId());
        List<UserTeam> userTeams = userTeamService.list(queryWrapper);

        // 取出不重复的队伍id
        // teamId  userId
        // 1       2
        // 1       3
        // 2       3
        // result
        // 1 => 2,3
        // 2 => 3
        Map<Long, List<UserTeam>> listMap = userTeams.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        ArrayList<Long> idList = new ArrayList<>(listMap.keySet());
        teamQuery.setIdList(idList);



        // 执行查询
        List<TeamUserVO> list = teamService.listTeams(teamQuery, true);
        return ResultUtils.success(list);
    }

}
